package com.sihai.core.utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

/**
 * 数组工具类
 */
public class ArrayUtils extends org.apache.commons.lang.ArrayUtils {

	private ArrayUtils() {
	}

	/**
	 * 将List转换成数组
	 *
	 * @param collection 需要转换的Collection
	 * @param elementType Collection中元素的类型
	 * @return 转换后的数组
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[] toArray(Collection<?> collection, Class<T> elementType) {
		if (collection == null) {
			return null;
		}
		if (collection.isEmpty()) {
			return null;
		}
		T[] array = (T[]) Array.newInstance(elementType, collection.size());
		collection.toArray(array);
		return array;
	}

	/**
	 * 抽取目标数组的某个属性并合成新数组
	 *
	 * @param <T>
	 * @param type
	 * @param target
	 * @param property
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[] extract(Class<T> type, Object[] target, String property) {
		if (target == null || target.length == 0) {
			return null;
		}
		List<T> extracted = new ArrayList<T>();
		for (Object current : target) {
			try {
				extracted.add((T) PropertyUtils.getProperty(current, property));
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
		return toArray(extracted, type);
	}

	/**
	 * 抽取目标数组的某个属性并合成新数组
	 *
	 * @param <T>
	 * @param type
	 * @param target
	 * @param property
	 * @return
	 */
	public static <T> T[] extract(Class<T> type, Collection<?> target, String property) {
		return extract(type, target.toArray(), property);
	}
}